/**
 * 前端db支持  还未开发好
 * @Author <175588516@qq.com> T 
 * @date 2024/11/11
 */
export default class DB{
	#request;//数据库打开对象
	#dbName;//数据库名
	#db;//数据库操作对象
	#storeName;//操作表名
	#defaultStoreName='mStoreDefault';//默认表名
	/**
	 * 初始化数据库
	 * @param {*} dbName 
	 * @param {*} storeName 数据直接保存的表
	 * @param {*} saveDate 数据直接保存的内容
	 * @returns 
	 */
	constructor(dbName){
		if(!window.indexedDB) return console.error('indexedDB is not supported');
		if(!dbName) return console.error('dbName is required');
		this.#dbName=dbName;
		const request = indexedDB.open(dbName, 1);
		this.#request=request;
		request.onupgradeneeded = this.onupgradeneeded
		request.onsuccess = this.onsuccess
		request.onerror = this.onerror
	}
	/**
	 * 数据库完成初始化
	 * @param {*} event 
	 */
	onupgradeneeded(event){
		console.log('createdDB',this.#dbName)
	    const db = event.target.result;
		this.#db=db;
		this.store(this.#defaultStoreName)
	}
	/**
	 * 数据库打开成功
	 * @param {*} event 
	 */
	onsuccess(event){
		const db = event.target.result;
		this.#db=db;
		console.log('Database opened successfully',db);
	}
	/**
	 * 数据库打开失败
	 * @param {*} event 
	 */
	onerror(event){
		console.error('Database error:', event.target.error);
	}
	/**
	 * 关闭数据库
	 */
	close(){
		this.#request.result.close();
	}
	/**
	 * 创建表或设置操作表
	 * @param {*} storeName 
	 */
	store(storeName,param={}){
		if(!storeName) return console.error('storeName is required');
		this.#storeName=storeName;
		// 检查对象存储是否已存在，避免重复创建
		if (!this.#db.objectStoreNames.contains(storeName)) {
			this.#db.createObjectStore(storeName, { keyPath: 'id',autoIncrement: true ,...param});
		}
		return this
	}
	// 给表设置索引
	setIndex(field=[],optoin){
		store.createIndex(...field, { unique: false ,...optoin});
	}
	/**
	 * 设置数据 存在主键则根据主键进行更新或插入，不存在则直接插入
	 * @param {*} storeName 
	 * @param {*} value 
	 * @param {*} modal 
	 * @returns 
	 */
	set(value={},modal='readwrite'){
		const storeName = this.getNowAndsetDefaultStore()
		return new Promise((resolve, reject) => {
			const transaction = this.#db.transaction(storeName, modal);
			const store = transaction.objectStore(storeName);
			store.add(value);
			transaction.oncomplete = () => {
				console.log('Data added successfully');
				resolve({status:true});
			}
			transaction.onerror = (event) => {
				console.error('Error adding data:', event.target.error);
				resolve({status:false,err:event.target.error});
			}
		})
	}
	/**
	 * 精确获取数据
	 * @param {*} id 
	 * @returns 
	 */
	get(id){
		if(!id) return console.error('id is required');
		const storeName = this.getNowAndsetDefaultStore()
		return new Promise((resolve, reject) => {
			const transaction = db.transaction(storeName, 'readonly');
			const store = transaction.objectStore(storeName);
			const request = store.get(id);
			request.onsuccess = (event) => {
				resolve(request.result)
			};
		})
	}
	clean(id) {
		const storeName = this.getNowAndsetDefaultStore()
	    const transaction = db.transaction(storeName, 'readwrite');
		const store = transaction.objectStore(storeName);
		store.delete(id);
	}
	// 查询top1数据
	find(search){

	}
	/**
	 * 条件查询所有数据
	 * @param {*} search 
	 */
	findAll(search){
		return this
	}
	/**
	 * 排序
	 */
	sort(orderBy){
		const index = table.index("ageIndex");
		// 遍历索引，按年龄升序排列
		const request = index.openCursor(null, "next"); // "next" 为升序, "prev" 为降序
		// 如果需要基于多个字段排序，可能需要组合字段来创建索引。
		return this
	}
	/**
	 * 使用分页查询
	 * @param {*} pageOption 
	 */
	page(pageOption){

	}
	// 遍历所有数据方法
	getAllData(db) {
		return new Promise((resolve, reject) => {
			const storeName = this.getNowAndsetDefaultStore()
			const transaction = db.transaction(storeName, 'readwrite');
			const store = transaction.objectStore(storeName);
			store.openCursor().onsuccess = (event) => {
				const cursor = event.target.result;
				if (cursor) {
					console.log('Record:', cursor.value);
					resolve(cursor.value)
					cursor.continue();
				}
			}
		})
	}
	getDb(){
	    return this.#db
	}
	// 返回当前应用表名并重置为默认表名
	getNowAndsetDefaultStore(){
		const storeName = this.#storeName
		this.#storeName=this.#defaultStoreName
		return storeName
	}
}